/*******************************************************************
 *  1. �뾽臾� �떆�뒪�뀥 紐� 	: 
 *  2. �떒�쐞 �떆�뒪�뀥 紐� 	: 怨듯넻
 *  3. �쐢�룄�슦 紐� 	    : 
 *  4. �봽濡쒓렇�옩 媛쒖슂 	: 湲곕낯 �쑀�떥
 *  5. 愿��젴 Table 	: 議고쉶 �뀒�씠釉� :
 *                    �뾽�뜲�씠�듃 �뀒�씠釉� : 
 *  6. �옉  �꽦  �옄 	: 
 *  8. �옉  �꽦  �씪 	:
 *  9. 二� �쓽 �궗 �빆 	: 
 *  10. �뙆�씪誘명꽣 �꽕紐� 	:
 *  11.	踰꾩쟾 	    	:
 *  12. 蹂�寃쎌옄 		: 
 *  13. 蹂�寃쎌씪�옄 		: 
 *  14. 蹂�寃쎌궗�쑀 		: 
*************************************************************************/

package comm;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;


public class BaseUtil
{	
	private final static int MILLIS_PER_HOUR = 3600000;		//60*60*1000

	private final static String defaultDateFormatter = "yyyyMMdd";
	private static Calendar CALENDAR = Calendar.getInstance();

	public static String cutString(String str, int length) {
		return cutString(str, length, "");
	}
	
	public static String cutString(String str, int length, String suffix) {
		if (str == null) return "";
		if (str.length() < length) return str;
		return str.substring(0, length) + suffix;
	}
	
	/**
	* 二쇱뼱吏� String�쓽 �삤瑜몄そ�뿉�꽌 �뒪�듃留곸쓣 �젣�쇅�븳 紐⑤뱺臾몄옄瑜� �뾾�븻�떎.
	* @param String 
	* @return String
	*/
	public static String stringTrim(String str)
	{
		if (str == null) return "";
		return str.trim();
	}
	
	/**
	* 二쇱뼱吏� String�씠 null�씪 寃쎌슦 怨듬갚臾몄옄濡� 諛섑솚�븳�떎.
	* @param String 
	* @return String
	*/
	public static String replaceBlank(String str)
	{
		if (str == null|| str.length() == 0) return "&nbsp;";
		return str;
	}
	
	/**
	* 二쇱뼱吏� String�쓽 媛믪씠 null�씪 寃쎌슦 0�쓣 由ы꽩�븳�떎.
	* @param String 
	* @return String
	*/
	public static String intTrim(String str)
	{
		if (str == null) return "0";
		return str.trim();
	}
	
	/**
	* 二쇱뼱吏� Object�쓽 �뒪�듃留곸쓣 �젣�쇅�븳 紐⑤뱺臾몄옄瑜� �뾾�븻�떎.
	* @param String 
	* @return String
	*/
	public static String objTrim(Object str)
	{
		String rtnVal = "";
		rtnVal = (String)str;
		if (rtnVal == null) return "";
		return rtnVal.trim();
	}

	/**
	* 二쇱뼱吏� String�쓽 �쇊履쎌쓽 鍮� 怨듬갚�쓣 �뾾�븻�떎.
	* @param String
	* @return String
	*/
	public static String stringLTrim(String str)
	{
		if (str == null) return "";

		while(str.startsWith(" ")) {
			str = str.substring(1, str.length());
		}
		return str;
	}

	/**
	* 二쇱뼱吏� String�쓽 �삤瑜몄そ�쓽 鍮� 怨듬갚�쓣 �뾾�븻�떎.
	* @param String
	* @return String
	*/
	public static String stringRTrim(String str)
	{
		if (str == null) return "";

		while(str.endsWith(" "))
		{
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	/**
	* �뒪�듃留곸쓽 �쇊履쎌뿉 二쇱뼱吏� 媛��닔留뚰겮 臾몄옄瑜� 遺숈씤�떎.
	* @param str
	* @param padChar padded character
	* @param padLen  padded length
	* @return String padded String
	*/
	public static String stringLPad(String str, char padChar, int padLen)
	{
		while (str.length() < padLen)
		{
			str = padChar + str;
		}

		return str;
	}

	/**
	* �뒪�듃留곸쓽 �삤瑜몄そ�뿉 二쇱뼱吏� 媛��닔留뚰겮 臾몄옄瑜� 遺숈씤�떎.
	* @param str
	* @param padChar padded character
	* @param padLen  padded length
	* @return String padded String
	*/
	public static String stringRPad(String str, char padChar, int padLen)
	{
		while (str.length() < padLen)
		{
			str = str + padChar;
		}

		return str;
	}

	/**
    * 二쇱뼱吏� �닔移섏뿉 �옄由ъ닔 留뚰겮 "0" �쓣 遺숈씤 �뒪�듃留곸쓣 �뼸湲곗쐞�븳 Static 硫붿냼�뱶
    * @param size	�뒪�듃留곸쑝濡� 蹂��솚 �븷 �쟾泥� �옄由� �닔
    * @param num	�뒪�듃留곸쑝濡� 蹂��솚 �븷 �닔移�
    * @return String	ex) "0001", "0000210"
    */
	public static String padNumber(int size, long num)
    {
        String s = "";
        for(int j = size - 1; j >= 0; j--)
        {
            long l1 = (long)Math.pow(10D, j);
            long l2 = num / l1;
            s = s + l2;
            num -= l2 * l1;
        }

        return s;
    }

	/**
	* �뵒�뤃�듃濡� 吏��젙�맂 Date�쓽 format�쓣 �뼸�뒗�떎.
	* @return String	ex) yyyyMMdd, yyyy-MM-dd HH:mm:ss
	*/
	public static String getFormatter()
	{
		return defaultDateFormatter;
	}

	/**
	* �뵒�뤃�듃濡� 吏��젙�맂 TimeZone�쓽 ID瑜� �뼸�뒗�떎.
	* @return String
	*/
	public static String getTimeZoneID()
	{
		//String str = BasePropManager.getBaseProperties("Environment").getString("ebiz21.date.timezone");
		//return (str == null) ? (TimeZone.getDefault()).getID() : str   ).toUpperCase();
		return ( TimeZone.getDefault() ).getID();
	}

	/**
	* �뵒�뤃�듃濡� 吏��젙�맂 TimeZone�쓽 RawOffset瑜� �뼸�뒗�떎.
	* @return String
	*/
	public static int getRawOffSet()
	{
		//int val = BasePropManager.getBaseProperties("Environment").getInt("ebiz21.date.rawoffset");
		//return (val == -1) ? ( TimeZone.getDefault() ).getRawOffSet() : val;
		return ( TimeZone.getDefault() ).getRawOffset();
	}

	/**
	* �뵒�뤃�듃濡� 吏��젙�맂 TimeZone�쓣 �뼸�뒗�떎.
	* @return SimpleTimeZone
	*/
	public static TimeZone getTimeZone()
	{
		return TimeZone.getDefault();
	}

	public static String getTime(long time) {
		SimpleDateFormat fmt = new SimpleDateFormat(getFormatter());
		fmt.setTimeZone( getTimeZone() );

		return fmt.format(new java.util.Date( time ));
	}
	
	/**
	* �쁽�옱�쓽 �떆媛꾩쓣 �뵒�뤃�듃濡� 吏��젙�맂 format �뒪�듃留곸쑝濡�  �뼸�뒗�떎.
	* @return String
	*/
	public static String getCurrentTime()
	{
		return getCurrentTime(   getFormatter()   );
	}

	/**
	* �쁽�옱�쓽 �떆媛꾩쓣 二쇱뼱吏� format �뒪�듃留곸쑝濡�  �뼸�뒗�떎.
	* @param formatter : yyyy-MM-dd,HH:mm:ss �벑�벑
	* @return String
	*/
	public static String getCurrentTime(String formatter)
	{
		SimpleDateFormat fmt = new SimpleDateFormat(formatter);
		fmt.setTimeZone( getTimeZone() );

		return fmt.format(new java.util.Date( System.currentTimeMillis() ));
	}

	/**
	* �쁽�옱 �떆媛꾩뿉 ����븳 java.util.Date媛앹껜瑜� �뼸�뒗�떎.
	* @return java.util.Date
	*/
	public static java.util.Date getCurrentDate()
	{
		return new java.util.Date( System.currentTimeMillis() );
	}

	/**
	* 二쇱뼱吏� �떆媛꾩뒪�듃留곸뿉 ����븳 java.util.Date媛앹껜瑜� �뼸�뒗�떎.
	* @param dt 	ex) 15:00:00
	* @return java.util.Date
	*/
	public static java.util.Date getCurrentDate(String dt)
	{
		if( dt.length() != 8 ) return null;
		
		Calendar cal = Calendar.getInstance();
		cal.set(
			cal.get(Calendar.YEAR),
			cal.get(Calendar.MONTH),
			cal.get(Calendar.DATE),
			Integer.valueOf( dt.substring(0,2) ).intValue(),
			Integer.valueOf( dt.substring(3,5) ).intValue(),
			Integer.valueOf( dt.substring(6,8) ).intValue()
		);

		return cal.getTime();
	}

	/**
	* 二쇱뼱吏� Date�뒪�듃留곸뿉 ����븳 java.util.Date媛앹껜瑜� �뼸�뒗�떎.
	* @param dt 	yyyyMMddHHmmss ex) 19000518120000
	* @return java.util.Date
	*/
	private static java.util.Date getUtilDate(String dt)
	{
		Calendar cal = Calendar.getInstance();
		cal.set(
			Integer.valueOf( dt.substring(0,4) ).intValue(),
			Integer.valueOf( dt.substring(4,6) ).intValue() - 1,
			Integer.valueOf( dt.substring(6,8) ).intValue(),
			Integer.valueOf( dt.substring(8,10) ).intValue(),
			Integer.valueOf( dt.substring(10,12) ).intValue(),
			Integer.valueOf( dt.substring(12,14) ).intValue()
		);

		return cal.getTime();
	}

	/**
	* 二쇱뼱吏� �궇吏� �뒪�듃留곸뿉 �닔移섎�� �뜑�븳 java.Util.Date媛앹껜瑜� �뼸�뒗�떎.
	* @ param dt	(yyyyMMdd or yyyyMMddHHmmss)
	* @ param day	二쇱뼱吏� �궇吏� �뒪�듃留곸뿉 �뜑�븷 �궇吏� �닔移�
	* @ return java.util.Date
	*/
	public static java.util.Date addDate(String dt, int day)
	{
		if (dt == null)
			throw new IllegalArgumentException("dt can not be null");

		int len = dt.length();
		if ( !(len == 8 || len == 14) )
			throw new IllegalArgumentException("dt length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");

		if (len == 8) dt += "000000";

		return addDate( getUtilDate(dt), day );
	}

	/**
	* 二쇱뼱吏� java.util.Date媛앹껜�뿉 �닔移섎�� �뜑�븳 java.Util.Date媛앹껜瑜� �뼸�뒗�떎.
	* @ param dt
	* @ param day	Date媛앹껜�뿉 �뜑�븷 �궇吏� �닔移�
	* @ return java.util.Date
	*/
	public static java.util.Date addDate(java.util.Date dt, int day)
	{
		return new java.util.Date( dt.getTime() + ((long) (MILLIS_PER_HOUR * 24 * day)) );
	}

	/**
	* 二쇱뼱吏� �떆媛� �뒪�듃留� from�뿉�꽌 to源뚯���쓽 �궇吏� �씪�닔瑜� �뼸�뒗�떎.
	* @param from (yyyyMMdd or yyyyMMddHHmmss)
	* @param to (yyyyMMdd or yyyyMMddHHmmss)
	* @return int
	*/
	public static int betweenDate(String from, String to)
	{
		if (from == null)
			throw new IllegalArgumentException("from can not be null");
		if (to == null)
			throw new IllegalArgumentException("to can not be null");

		int len = from.length();
		if ( !(len == 8 || len == 14) )
			throw new IllegalArgumentException("from length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");

		if (len == 8) from += "000000";

		len = to.length();
		if ( !(len == 8 || len == 14) )
			throw new IllegalArgumentException("to length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");

		if (len == 8) to += "000000";

		return betweenDate( getUtilDate(to), getUtilDate(from) );
	}

	/**
	* 二쇱뼱吏� java.util.Date媛앹껜 from�뿉�꽌 to源뚯���쓽 �궇吏� �씪�닔瑜� �뼸�뒗�떎.
	* @param from
	* @param to
	* @return int
	*/
	public static int betweenDate(java.util.Date from, java.util.Date to)
	{
		return new Long( (to.getTime() - from.getTime()) / (MILLIS_PER_HOUR * 24) ).intValue();
	}

	/**
	* 二쇱뼱吏� �떆媛� �뒪�듃留곸쓣 二쇱뼱吏� �룷留룹쑝濡� 蹂��솚�븳�떎.
	* @param dt (yyyyMMdd or yyyyMMddHHmmss)
	* @param formatter (yyyyMMdd.....)
	* @return String
	*/
	public static String convertDateFormat(String dt, String formatter)
	{
		if (dt == null)
			throw new IllegalArgumentException("dt can not be null");

		int len = dt.length();
		if ( !(len == 8 || len == 14) )
			throw new IllegalArgumentException("dt length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");

		if (dt.length() == 8) dt += "000000";

		SimpleDateFormat sdf = new SimpleDateFormat(formatter);
		return sdf.format( getUtilDate(dt) );
	}

	/**
	* 二쇱뼱吏� java.sql.Date媛앹껜瑜� 二쇱뼱吏� �룷留룹쑝濡� 蹂��솚�븳�떎.
	* @param dt
	* @param formatter (yyyyMMdd.....)
	* @return String
	*/
	public static String convertDateFormat(java.sql.Date dt, String formatter)
	{
		return convertDateFormat( (java.util.Date) dt, formatter );
	}

	/**
	* 二쇱뼱吏� java.sql.Timestamp媛앹껜瑜� 二쇱뼱吏� �룷留룹쑝濡� 蹂��솚�븳�떎.
	* @param dt
	* @param formatter (yyyyMMdd.....)
	* @return String
	*/
	public static String convertDateFormat(java.sql.Timestamp dt, String formatter)
	{
		return convertDateFormat((java.util.Date) dt, formatter);
	}
	/**
	* 二쇱뼱吏� java.util.Date媛앹껜瑜� 二쇱뼱吏� �룷留룹쑝濡� 蹂��솚�븳�떎.
	* @param dt
	* @param formatter (yyyyMMdd.....)
	* @return String
	*/
	public static String convertDateFormat(java.util.Date dt, String formatter)
	{
		SimpleDateFormat sdf = new SimpleDateFormat( formatter );
		return sdf.format(dt);
	}

	/**
	* 二쇱뼱吏� �떆媛� �뒪�듃留곸쓣 java.sql.Date媛앹껜濡� 蹂��솚�븳�떎. 
	* @param dt (yyyyMMdd or yyyyMMddHHmmss)
	* @return java.sql.Date
	*/
	public static java.sql.Date toSQLDate(String dt)
	{
		return (java.sql.Date) toUtilDate(dt);
	}

	/**
	* 二쇱뼱吏� �떆媛� �뒪�듃留곸쓣 java.util.Date媛앹껜濡� 蹂��솚�븳�떎. 
	* @param dt (yyyyMMdd or yyyyMMddHHmmss)
	* @return java.util.Date
	*/
	public static java.util.Date toUtilDate(String dt)
	{
		if (dt == null)
			throw new IllegalArgumentException("dt can not be null");

		int len = dt.length();
		if ( !(len == 8 || len == 14) )
			throw new IllegalArgumentException("dt length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");

		if (dt.length() == 8) dt += "000000";

		return getUtilDate(dt);
	}

	public static String makeMoneyType(String no)
	{
		int index = no.indexOf(".");
		if (index == -1)
		{
			return BaseUtil.makeMoneyType( Long.parseLong(no) );
		}
		else
		{
			return (BaseUtil.makeMoneyType( Long.parseLong(no.substring(0, index)) ) + no.substring(index, no.length()) );
		}
	}
	public static String makeMoneyType(int no)
	{
		return ( BaseUtil.makeMoneyType( new Integer(no).longValue() ) );
	}
	public static String makeMoneyType(long no)
	{
		return NumberFormat.getInstance().format(no);
	}
	public static String makeMoneyType(double no)
	{
		return NumberFormat.getInstance().format(no);
	}
	public static String makeMoneyType(float no)
	{
		return ( BaseUtil.makeMoneyType( new Float(no).doubleValue() ) );
	}

	/**
	* 二쇱뼱吏� �듅�닔臾몄옄 �뒪�듃留곸쓣 HTML濡� 蹂��솚�븳�떎. 
	* @param src 	�듅�닔臾몄옄 �뒪�듃留� ex) "<>&\n\t \"
	* @return String	HTML濡� 蹂��솚�맂 �뒪�듃留� ex) "&lt; &gt; &amp; &nbsp; &quot;"
	*/
	public static String convertHTML(String src)
	{
		if (src == null) return "";

		char[] arr = src.toCharArray();
		StringBuffer sb = new StringBuffer();

		for (int i=0; i<arr.length; i++)
		{
			switch (arr[i])
			{
				case '<'	:
					sb.append("&lt;");						break;
				case '>'	:
					sb.append("&gt;");						break;
				case '&'	:
					sb.append("&amp;");						break;
				case '\n'	:
					sb.append("<br />");						break;
				case '\t'	:
					sb.append("&nbsp;&nbsp;&nbsp;");		break;
				case ' ':
					sb.append("&nbsp;");					break;
				case '\"':
					sb.append("&quot;");					break;
				default	:
					sb.append(arr[i]);
			}
		}

		return sb.toString();
	}
	
	public static String convertHTML_GAUCE(String src)
	{
		if (src == null) return "";

		char[] arr = src.toCharArray();
		StringBuffer sb = new StringBuffer();

		for (int i=0; i<arr.length; i++)
		{
			switch (arr[i])
			{
				case '<'	:
					sb.append("&lt;");						break;
				case '>'	:
					sb.append("&gt;");						break;
				case '\"':
					sb.append("&quot;");					break;
				case '&'	:
					sb.append("&amp;");						break;
				default	:
					sb.append(arr[i]);
			}
		}

		return sb.toString();
	}
	
	/**
	 * 二쇱뼱吏� �듅�닔臾몄옄 �뒪�듃留곸쓣 HTML濡� 蹂��솚�븳�떎. 
	 * @param src	�듅�닔臾몄옄 �뒪�듃留� ex) \n
	 * @return String	HTML濡� 蹂��솚�맂 �뒪�듃留� ex) "<br />"
	 */
	public static String convertOnlyBR(String src) {
		
		if (src == null) return "";

		char[] arr = src.toCharArray();
		StringBuffer sb = new StringBuffer();

		for (int i=0; i<arr.length; i++)
		{
			switch (arr[i])
			{
				case '\n'	:
					sb.append("<br />");						break;
				default	:
					sb.append(arr[i]);
			}
		}

		return sb.toString();
	}
	
	/**
	* 二쇱뼱吏� �듅�닔臾몄옄 �뒪�듃留곸쓣 HTML濡� 蹂��솚�븳�떎. 
	* @param src 	�듅�닔臾몄옄 �뒪�듃留� ex) "<>&\n\t \"
	* @return String	HTML濡� 蹂��솚�맂 �뒪�듃留� ex) "&lt; &gt; &amp; &nbsp; &quot;"
	*/
	public static String convertBR(String src)
	{
		return convertHTML(src);
	}

	/**
	*	�듅�젙 臾몄옄�뿴濡� 援щ텇�맂 臾몄옄�뿴�쓣 遺꾨━�븯�뿬 諛곗뿴濡� 由ы꽩�븳�떎.
	*	@param	str	string separated string
	*	@param	strDelim		separating string
	*	@return	String[]
	*/
	public static String[] getTokenArray(String str)
	{
		return getTokenArray(str, ",");
	}
	public static String[] getTokenArray(String str, String strDelim)
	{
		if (str == null || str.length() == 0) return null;
		StringTokenizer st = new StringTokenizer(str, strDelim);

		String arrToken [];
		arrToken = new String[st.countTokens()];

		int i = 0;
		while (st.hasMoreTokens())
		{
			arrToken[i] = st.nextToken();
			i++;
		}

		return arrToken;
	}

	/**
    * �쁽�옱(�븳援�湲곗��) �떆媛꾩젙蹂대�� �뼸�뒗�떎.                     <BR>
    * (�삁) �엯�젰�뙆由щ�명꽣�씤 format string�뿉 "yyyyMMddhh"瑜� �뀑�똿�븯硫� 1998121011怨� 媛숈씠 Return.  <BR>
    * (�삁) format string�뿉 "yyyyMMddHHmmss"瑜� �뀑�똿�븯硫� 19990114232121怨� 媛숈씠
    *      0~23�떆媛� ����엯�쑝濡� Return. <BR>
    *      String CurrentDate = BaseUtil.getKST("yyyyMMddHH");<BR>

    * @param    format      �뼸怨좎옄�븯�뒗 �쁽�옱�떆媛꾩쓽 Type
    * @return   str 		�쁽�옱 �븳援� �떆媛�.
    */
    public static String getKST(String format)
    {
	  	//1hour(ms) = 60s * 60m * 1000ms
        //int millisPerHour = 60 * 60 * 1000;
        SimpleDateFormat fmt= new SimpleDateFormat(format);

        //SimpleTimeZone timeZone = new SimpleTimeZone(9*MILLIS_PER_HOUR,"KST");
        //fmt.setTimeZone(timeZone);
        fmt.setTimeZone(BaseUtil.getTimeZone());

        long time=System.currentTimeMillis();
        String str=fmt.format(new java.util.Date(time));
        //BaseLogManager.trace("[Date="+str);
        return str;
   }

   /**
    * �쁽�옱(�븳援�湲곗��) �떆媛꾩젙蹂대�� �뼸�뒗�떎.                     	<BR>
    * informix�쟾�슜�쓽 DATE 愿��젴�옄猷뚰삎�쓽 �몴湲곕쾿�쓣 �뵲瑜몃떎.		<BR>
    * �몴湲곕쾿��� yyyy-mm-dd 									<BR>
    * @param   N/A
    * @return   String 		yyyy-mm-dd�삎�깭�쓽 �쁽�옱 �븳援��떆媛�.             <BR>
    */
	public static String getKSTDate()
   	{
   			//SimpleTimeZone pdt = new SimpleTimeZone(9 * 60 * 60 * 1000, "KST");

			// Format the current time.
			SimpleDateFormat formatter
				= new SimpleDateFormat ("yyyyy-MM-dd");
			Date currentTime_1 = new Date();
			return formatter.format(currentTime_1);
	}

   /**
    * �쁽�옱(�븳援�湲곗��) �떆媛꾩젙蹂대�� �뼸�뒗�떎.                     	<BR>
    * informix�쟾�슜�쓽 DATETIME 愿��젴�옄猷뚰삎�쓽 �몴湲곕쾿�쓣 �뵲瑜몃떎. 	<BR>
    * �몴湲곕쾿��� yyyy-mm-dd hh:mm:ss 							<BR>
    * @param    N/A														<BR>
    * @return   String 		yyyy-mm-dd hh:mm:ss�삎�깭�쓽 �쁽�옱 �븳援��떆媛�.    <BR>
    */
	public static String getKSTDateTime()
   	{
   			//SimpleTimeZone pdt = new SimpleTimeZone(9 * 60 * 60 * 1000, "KST");

			// Format the current time.
			SimpleDateFormat formatter
				= new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
			Date currentTime_1 = new Date();
			return formatter.format(currentTime_1);
	}//end method

   /**
    * java.sql.Date object瑜� �뼸湲� �쐞�븳 寃�     <BR>
	*
    * �뜲�씠釉� 援ъ꽦 :	timetable (a DATE, b DATETIME YEAR TO SECOND)
	*
    * (�삁)
	*	   PreparedStatement	pstmt = conn.prepareStatement("Insert into timetable values (?, ? )" );
	*	   pstmt.setDate( 1, CSaUtil.getDate("1999-10-10");
	*
    * @param    dateString  		�궇吏쒕Ц�옄�뿴(yyyy-mm-dd)
    * @return   java.sql.Date
    */
	public static java.sql.Date getDate(String in_time)
	{
		return java.sql.Date.valueOf(in_time);
	}

    /**
   	* �엯�젰�븳 �궇吏� 湲곗���쑝濡� 紐뉗씪 �쟾,�썑
   	* (二쇱쓽)�엯�젰�궇吏쒕뒗 援щ텇�옄媛� �뾾�뒗 string�삎
	* @param	dayString	string date (19991002)
	* @param	day			�뜑�븯嫄곕굹 鍮쇰젮�뒗 �떆媛�
	* @return	String
   	*/
   	public static String getDateWithSpan(String dayString, int day)
   	{
        //int millisPerHour = 60 * 60 * 1000;
        SimpleDateFormat fmt= new SimpleDateFormat("yyyy-MM-dd");
        //SimpleTimeZone timeZone = new SimpleTimeZone(9*MILLIS_PER_HOUR,"KST");
        //fmt.setTimeZone(timeZone);
		fmt.setTimeZone(BaseUtil.getTimeZone());

        int y = Integer.parseInt( dayString.substring(0,4) );
		int m = Integer.parseInt( dayString.substring(4,6) );
		int d = Integer.parseInt( dayString.substring(6,8) );

		Calendar aCalendar = Calendar.getInstance();
		aCalendar.set(y, m+day, d+day);

		int year = aCalendar.get(Calendar.YEAR);
		int month = aCalendar.get(Calendar.MONTH) + 1;
		int date = aCalendar.get(Calendar.DATE);

		return fmt.format( Integer.toString(year) +
						   ((month<10) ? "0" + Integer.toString(month) : Integer.toString(month)) +
						   ((date<10) ? "0" + Integer.toString(date) : Integer.toString(date))
						  );
	}

    /**
   	* �엯�젰�븳 �궇吏� 湲곗���쑝濡� �쟾�궇吏쒕�� �깮�꽦
   	* (二쇱쓽)�엯�젰�궇吏쒕뒗 援щ텇�옄媛� �뾾�뒗 string�삎
	* @param	dayString	string date (19991002)
	* @return	String
   	*/
   	public String getPrevDate(String dayString)
	{
		int y = Integer.parseInt( dayString.substring(0,4) );
		int m = Integer.parseInt( dayString.substring(4,6) );
		int d = Integer.parseInt( dayString.substring(6,8) );

		Calendar aCalendar = Calendar.getInstance();
		aCalendar.set(y, m-1, d-1);

		int year = aCalendar.get(Calendar.YEAR);
		int month = aCalendar.get(Calendar.MONTH) + 1;
		int date = aCalendar.get(Calendar.DATE);

		return  Integer.toString(year) +
				((month<10) ? "0" + Integer.toString(month) : Integer.toString(month)) +
				((date<10) ? "0" + Integer.toString(date) : Integer.toString(date));
	}

   /**
    * String�쓣 int媛믪쑝濡� 蹂��솚�븳�떎.           <BR>
    * int cnt = BaseUtil.stoi("10");	<BR>
    * @param    str     int媛믪쑝濡� 蹂��솚�맆 String臾몄옄�뿴.
    * @return   蹂��솚�맂 int 媛�.
    */
    public static int stoi(String str)
    {
        if(str == null ) return 0;
        return (Integer.valueOf(str).intValue());
    }

   /**
    * int媛믪쓣 String�쑝濡� 蹂��솚�븳�떎.           <BR>
    * �삁) Strint str = BaseUtil.itos(10);	<BR>
    * @param    i   String�쑝濡� 蹂��솚�맆 int 媛�.
    * @return   蹂��솚�맂 String 媛�.
    */
    public static String itos(int i)
    {
        return (new Integer(i).toString());
    }
    
    
    /**
     * �꽭�옄由щ쭏�떎 ,瑜� 李띾뒗�떎.           <BR>
     * @param    valNum   蹂��솚�맆 int 媛�.
     * @return   蹂��솚�맂 ,瑜� �룷�븿�븳 媛�.
     */
      public static String numFormat(int valNum) throws Exception { 
            
    	  	String returnval = "";
    	  
            DecimalFormat df = new DecimalFormat("#,###");       // �꽭�옄由� 留덈떎 ','瑜� 異붽�� 
            returnval = df.format(valNum); 
            
            return returnval;
      } 

      public static String percentFormat(double valNum) throws Exception { 
          
  	  	String returnval = "";
  	  
          DecimalFormat df = new DecimalFormat("##.##");       // �꽭�옄由� 留덈떎 ','瑜� 異붽�� 
          returnval = df.format(valNum); 
          
          return returnval;
    } 


	/**
	* �뜲�씠���踰좎씠�뒪濡� 臾몄옄�뿴�쓣 ����옣�븯湲� �쟾�뿉 蹂��솚
	* (二쇱쓽) �븳湲�蹂��솚�쓣 �쐞�븯�뿬 �궗�슜
	* @param	str			DB濡� ����옣�븷 �븳湲��씠 �뱾�뼱�엳�뒗 臾몄옄�뿴
	* @return	tmpStr		8859_1 codeset�쑝濡� 蹂��솚�맂 臾몄옄�뿴
	*/
    public static String toDB(String str)
    {
    	String tmpStr = new String();
    	try
    	{
    		return Ksc2Uni(str);
		}
		catch(UnsupportedEncodingException e)
		{
			e.printStackTrace(System.err);
		}

		return tmpStr;


    }


	/**
	* �뜲�씠���踰좎씠�뒪濡쒕���꽣 �뼸��� 臾몄옄�뿴�쓣 蹂��솚
	* (二쇱쓽) �븳湲�蹂��솚�쓣 �쐞�븯�뿬 �궗�슜�븿
	* @param	str			DB�뿉�꽌 媛��졇�삩 �븳湲��씠 �뱾�뼱�엳�뒗 臾몄옄�뿴
	* @return	tmpStr		KSC5601 codeset�쑝濡� 蹂��솚�맂 臾몄옄�뿴
	*/
    public static String fromDB(String str)
    {
    	String tmpStr = new String();
    	try
    	{
    		tmpStr = Uni2Ksc(str);
		}
		catch(UnsupportedEncodingException e)
		{
			e.printStackTrace(System.err);
		}

		return tmpStr;
    }

	/**
	* Ksc5601 ---> 8859_1 臾몄옄�뿴濡� 蹂��솚
    * �삁) Strint str = BaseUtil.Ksc2Uni("�젣紐�:\n");	<BR>
	* @param	KscStr
	* @return	String
	*/
    public static String Ksc2Uni(String KscStr)
        throws java.io.UnsupportedEncodingException
	{
		if(KscStr == null)
		{
			return null;
		}
		else
		{
			return new String (KscStr.getBytes("KSC5601"), "8859_1");
		}
	}


   /**
	* 8859_1 ---> Ksc5601 臾몄옄�뿴濡� 蹂��솚
	*
	* @param	UnicodeStr
	* @return	String
	*/
	public static String Uni2Ksc(String UnicodeStr)
		throws UnsupportedEncodingException
	{
		if(UnicodeStr == null)
		{
			return null;
		}
		else
		{
			return new String (UnicodeStr.getBytes("8859_1"), "KSC5601");
		}
	}

	/**
    * query string�쓣 parsing�븳�떎.             <BR>
    *
    * @param    queryString queryString.
    * @param    indexParam  parsing�븯怨좎옄 �븯�뒗 �씤�뜳�뒪臾몄옄�뿴.
    * @return   �씤�뜳�뒪臾몄옄�뿴�뿉 �쓽�빐 parsing�맂 value媛�.
    */
    public static String parseQueryString(String queryString, String indexParam)
    {
		int start;
		int howLong;

		queryString += "&"; 			    // �걹�몴�떆 異붽��
		indexParam += "=";			    // '='異붽��
		start = queryString.indexOf(indexParam, 0); // �썝�븯�뒗 indexParam�쓽 value 泥� �쐞移섎�� �븣�븘�궦�떎.
		if(start == -1) return "";
		start += indexParam.length();
		howLong = queryString.indexOf("&", start ); 	// value�쓽 湲몄씠瑜� �븣�븘�궦�떎.
		if( howLong < (start + 1) )	return "";	// last value==NULL

		String temp = queryString.substring( start, howLong );
        int idx = temp.indexOf("%20");
        while (idx != -1)
        {
            temp = temp.substring(0,idx) +" "+ temp.substring(idx+3,temp.length());
            idx = temp.indexOf("%20");
        }
        return temp;

    }

  /**
    * exception 諛쒖깮�떆�뿉 alert 硫붿꽭吏�瑜� 蹂댁뿬以��떎.           <BR>
    *
    * @param    out     PrintWriter object
    * @param    str     cct exception message
    * @return   N/A
    */
    public static void printAlert(PrintWriter out, String str)
    {
        out.println("<HTML>\n");
        out.println("<HEAD>\n");
        out.println("<SCRIPT LANGUAGE = \"JavaScript\"> ");
   		out.println("    history.back()     ");
		if ( str == null )
		{
		    str = "Servlet UI Class Exception \\n \\n Please Check Your Code ";
		}
		out.println("    alert(\""+str+"\")");
        out.println("</SCRIPT>" );
        out.println("</HEAD>\n");
        out.println("<BODY>");
        out.println("<H3>");
        out.println("Error<BR>");
        out.println("</H3><PRE>");
        out.println("CctException : "+ str );
        out.println("</PRE></BODY>\n");
        out.println("</HTML>\n");
    }

   /**
    * parseAppErrorCode                                            <BR>
    * exception 諛쒖깮�떆�뿉 alert 硫붿꽭吏��쓽 �뒪�듃留곸쨷�뿉�꽌 Error Code留뚯쓣<BR>
    * return�븳�떎.  <br>
    * @param    errString     e.getMessage()
    * @return   errorCode     Error Code
    */
    public static String parseAppErrorCode(String errString) //throws Exception
    {
        //if (errString.length() < 1 ) throw new Exception("errString.length() = 0");

        int firstIdx = errString.indexOf("ORA-")+4;
//        int secondIdx = errString.indexOf("\\n");
        String appErrCode = errString.substring(firstIdx,firstIdx + 5);
        return appErrCode;
    }

	public static void toHex(String str)
	{
		for ( int i=0;i<str.length();i++)
		{
			System.out.println(Integer.toHexString(str.charAt(i)&0xff));
		}
	}


    /**
     * 臾몄옄�뿴�뿉�꽌 �듅�젙 臾몄옄�뿴�쓣 �썝�븯�뒗 臾몄옄�뿴濡� 蹂�寃� �븳�떎<br>
     * �궗�슜�삁 ) String kk�뿉�꽌 "ddd"�씪�뒗 臾몄옄瑜� "ki"濡� 蹂�寃쏀븯怨� �떗��� 寃쎌슦
     * convertString(kk, "ddd", "ki")
     *
     * @param String targetStr 
     * @param String targetStr 
     * @param String targetStr 
     * @return String
     */
	public static String convertString(String targetStr, String fromStr, String toStr){
		int targetStrLen = targetStr.length();
		int fromStrLen = fromStr.length();
		String rstStr = "";
		
		if(targetStrLen < 1) return targetStr;
		
		int i=0;
		while(true){
			if(i+fromStrLen > targetStrLen) {
			rstStr += targetStr.substring(i, targetStrLen);
			break;
		}
	
		if(fromStr.equals(targetStr.substring(i, i+fromStrLen)) ){
			rstStr += toStr;
			i += fromStrLen;
		}else{
			rstStr += targetStr.substring(i, i+1);
			i++;
		}
	}
	
	return rstStr;
	
	}


    public static int realLength(String str)
    {
        int len = str.length();
        int cnt=0, index=0;

	    if (str == null ) return cnt;

        while (index < len)
        {
            if (str.charAt(index++) < 256) // 1諛붿씠�듃 臾몄옄�씪硫�...
                cnt++;     // 湲몄씠 1 利앷��
            else // 2諛붿씠�듃 臾몄옄�씪硫�...
                cnt += 2;  // 湲몄씠 2 利앷��
        }
        
        return cnt;
    }
    
    /**
     * �뙆�씪 �뾽濡쒕뱶�떆 �뤃�뜑媛� �뾾�뒗寃쎌슦 �뤃�뜑�깮�꽦<br>
     * @param dir �깮�꽦�븷 �뤃�뜑紐�
     */
	public static void makeDir(String dir)	{
		File f = new File(dir);
		if (!f.exists()) {
               f.mkdirs();
		 }
	}
	

	/**
	 * �옄諛붿뒪�겕由쏀듃 alert() �샇異�
	 * 
	 * @param out 
	 * @param msg
	 */
	public static void alert(JspWriter out, String msg) throws IOException {
		out.print("<script language=javascript> alert(' "+ msg + "');</script>");
	}
	
	/**
	 * �옄諛붿뒪�겕由쏀듃 alert() �샇異� �뮘 �씠�쟾 �럹�씠吏�濡� �씠�룞
	 * 
	 * @param out
	 * @param msg
	 */
	public static void alertAndBack(JspWriter out, String msg) throws IOException {
		out.print("<script language=javascript> alert(' "+ msg + "');history.back();</script>");
	}
	

	/**
	 * �옄諛붿뒪�겕由쏀듃濡� �긽�쐞 �럹�씠吏� �럹�씠吏� �씠�룞
	 * 
	 * @param out
	 * @param url
	 */
	public static void location2(JspWriter out, String url) throws IOException {
		out.print("<script language=javascript> parent.location.href=\"" + url + "\"; </script>");
	}
	
	/**
	 * �옄諛붿뒪�겕由쏀듃濡� �럹�씠吏� �씠�룞
	 * 
	 * @param out
	 * @param url
	 */
	public static void location(JspWriter out, String url) throws IOException {
		out.print("<script language=javascript> location.href=\"" + url + "\"; </script>");
	}
	
	/**
	 * int�삎 �뙆�씪誘명꽣 由ы꽩
	 * 
	 * @param request
	 * @param parameter
	 * @return �뙆�씪誘명꽣媛� �뾾�쑝硫� 0 由ы꽩
	 */
	public static int getIntParameter(HttpServletRequest request, String parameter) {
		return getIntParameter(request, parameter, 0);
	}

	/**
	 * int�삎 �뙆�씪誘명꽣 由ы꽩
	 * 
	 * @param request
	 * @param parameter
	 * @param defaultValue
	 * @return �뙆�씪誘명꽣媛� �뾾�쑝硫� defaultValue 由ы꽩
	 */
	public static int getIntParameter(HttpServletRequest request, String parameter, int defaultValue) {
		int value = defaultValue;
		if ( request.getParameter(parameter) != null ) {
			try {
				value = Integer.parseInt(request.getParameter(parameter));
			} catch (NumberFormatException ex) { }
		}
		return value;
	}
	
	/**
	 * checkbox �뙆�씪誘명꽣 由ы꽩
	 * 
	 * @param request
	 * @param parameter
	 * @return 泥댄겕�뻽�쑝硫� "Y", �븞 �뻽�쑝硫� "N" 由ы꽩
	 */
	public static String getCheckboxParameter(HttpServletRequest request, String parameter) {
		return "on".equals(request.getParameter(parameter)) ? "Y" : "N";
	}
	
	public static String getCheckboxParameter2(HttpServletRequest request, String parameter) {
		return "on".equals(request.getParameter(parameter)) ? "Y" : "";
	}
	
	//�뙆�씪 ����엯蹂꾨줈 �씠誘몄��瑜� �샇異쒗븳�떎.
	public static String getExtImg(String filename){
		if (filename == null || filename.equals("") || filename.indexOf('.') == -1) {
			return "<img src='/image/common/icon_non.gif' width='16' height='16' align='absmiddle'>";
		}
		String ext = filename.substring(filename.lastIndexOf('.')+1).toLowerCase();
		
		String file_type = "doc,exe,fla,gif,htm,hwp,jpg,mp3,pdf,ppt,swf,xls,zip";
		
		
		if ("html".equals(ext)) {
			ext = "htm";
		}
		
		if (file_type.indexOf(ext) > -1) {
			return "<img src='/image/common/icon_"+ext+".gif' width='16' height='16' align='absmiddle'>";
		}else{
			return "<img src='/image/common/icon_file.gif' width='16' height='16' align='absmiddle'>";
		}
	}
	
	/**
	  * 臾몄옄�뿴�궡�쓽 HTML�깭洹몃�� 紐⑤몢 �젣嫄�.
	  * PHP�쓽 stripTags() 李몄“.
	  *
	  * @see		#htmlSpecialChars
     * @see        <a href="http://www.php.net">PHP 李몄“</a>
     */
	public static String stripTags(String s)
	{
		StringBuffer buffer = new StringBuffer();
		StringTokenizer st = new StringTokenizer(s, "<>", true);
		String token;
		boolean inTag = false;
		while(st.hasMoreTokens()) {
			token = st.nextToken();
			switch(token.charAt(0)) {
			case '<':	inTag = true; break;
			case '>':	inTag = false; break;
			default:
				if(!inTag) buffer.append(token);
				else {
				}
			}
		}
		return buffer.toString();
	} 

	/**
	 * yyyyMMdd -> yyyy.MM.dd
	 * yyyy-MM-dd -> yyyy.MM.dd
	 * 
	 * @param date
	 * @return
	 */
	public static String toDotFormatDate(String date) {
		if (date != null && date.length() == 8) {
			return date.substring(0, 4) + '.' + date.substring(4,6) + '.' + date.substring(6,8);
		} else if (date != null && date.length() == 10) {
			return date.replace('-', '.');
		} else {
			return date;
		}		
	}

	public static String base64Encode(String plainText) {
		byte[] buf = plainText.getBytes(); 
		String encodedText = null; 
	    try {  
	    	// Convert a byte array to base64 string  
	    	encodedText = new sun.misc.BASE64Encoder().encode(buf);  
	    } catch (Exception e) {  
	    	e.printStackTrace(); 
	    } 
	    return encodedText; 
	} 
	   
	public static String base64Decode(String encodedText) { 
		byte[] buf = null; 
		String plainText = null; 
		try {  
			// Convert base64 string to a byte array  
			buf = new sun.misc.BASE64Decoder().decodeBuffer(encodedText);  
			plainText = new String(buf); 
		} catch (IOException e) {  
			e.printStackTrace(); 
		} 
		return plainText; 
	}
	
	public static String getRandomString(int len){ 
		Random random =new Random(); 
		char alphaNum[] = {'0','1','2','3','4','5','6','7','8','9'}; 
		String str = ""; 
		for(int j = 0; j < len ; j++) 
		{ 
		str = str + alphaNum[ random.nextInt(10) ]; 
		} 

		return str; 
	}

    public static long getPreviousMonth(long date) {
        return incrementMonth(date, -1);
    }

    public static long getNextMonth(long date) {
        return incrementMonth(date, 1);
    }

    private static long incrementMonth(long date, int increment) {
        Calendar calendar = CALENDAR;
        synchronized(calendar) {
            calendar.setTimeInMillis(date);
            calendar.add(Calendar.MONTH, increment);
            return calendar.getTimeInMillis();
        }
    }

    public static long getStartOfMonth(long date) {
        return getMonth(date, -1);
    }

    public static long getEndOfMonth(long date) {
        return getMonth(date, 1);
    }

    private static long getMonth(long date, int increment) {
		long result;
        Calendar calendar = CALENDAR;
        synchronized(calendar) {
            calendar.setTimeInMillis(date);
            if (increment == -1) {
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                result = startOfDayInMillis(calendar.getTimeInMillis());
            } else {
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.add(Calendar.MILLISECOND, -1);
                result = calendar.getTimeInMillis();
            }
        }
		return result;
    }
    
    public static long startOfDayInMillis(long date) {
        Calendar calendar = CALENDAR;
        synchronized(calendar) {
            calendar.setTimeInMillis(date);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            return calendar.getTimeInMillis();
        }
    }
    
    public static String getAllParams(HttpServletRequest request, String exclusiveParam, String ampChar) throws UnsupportedEncodingException {
		Enumeration paramNames = request.getParameterNames();
		StringBuffer param = new StringBuffer();
		while (paramNames.hasMoreElements()) {
			String k = (String) paramNames.nextElement();
			String v = URLEncoder.encode(request.getParameter(k), "UTF-8");
			if (!k.equals(exclusiveParam) && !k.equals("resultCode")) {
				param.append(ampChar + k + "=" + v);
			}
		}
		return param.toString();
	}
    public static String getAllParams(HttpServletRequest request, String exclusiveParam) throws UnsupportedEncodingException {
    	return getAllParams(request, exclusiveParam, "&amp;");
	}
	public static String getAllParams(HttpServletRequest request) throws UnsupportedEncodingException {
		return getAllParams(request, null);
	}
	/**
	 * null 泥댄겕 諛� 湲곕낯 媛� �뀑�똿
	 * @param param
	 * @param defValue
	 * @return
	 */
	public static String getParame(String param, String defValue){
		
		String returnValue = (param == null ? defValue : param);
		if("".equals(returnValue) || "null".equals(returnValue)){
			returnValue = defValue;
		}
		return returnValue;
	}	
	/**
	 * �솗�옣�옄瑜� 湲곕컲�쑝濡� �씠誘몄�� �뙆�씪�씤吏� 寃��궗
	 * 
	 * @param filename
	 * @return
	 */
	public static boolean checkImageFile(String filename) {
		int dot = filename.lastIndexOf('.');
		if (dot == -1) {
			return false;
		}
		String ext = filename.substring(dot+1).toLowerCase();
		if (ext.equals("jpg") || ext.equals("gif") || ext.equals("png")) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * �솗�옣�옄瑜� 湲곕컲�쑝濡� 泥⑤���뙆�씪 寃��궗
	 * 
	 * @param filename
	 * @return
	 */
	public static boolean checkFile(String filename) {
		int dot = filename.lastIndexOf('.');
		if (dot == -1) {
			return false;
		}
		String ext = filename.substring(dot+1).toLowerCase();
		if (ext.equals("jsp") || ext.equals("exe") || ext.equals("php") || ext.equals("asp") || ext.equals("js") || ext.equals("hr")) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * �삤�뒛 �궇吏쒖쓽 �뀈 �썡�쓣 由ы꽩�븯�뒗 硫붿냼�뱶
	 * @return �삤�뒛�궇吏�
	 */
    public static String getCurrentDate2()
    {
        Date date = new Date();
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
        String s = simpledateformat.format(date);
		return s;
    }
	
}

